<template>
  <div class="container" ref="mainCon">
    <topTitle
      titleText="设备任务列表"
      :back="true"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon">
      <el-row class="searchBox searchInputWidth">
        <el-form
          :inline="true"
          :model="filterField"
          ref="accountForm"
          label-width="80px"
        >
          <el-col :lg="8" :xl="6">
            <el-form-item label="任务类型" class="row-padding-bottom">
              <el-select
                v-model="filterField.type"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item of typeOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="处理状态" class="row-padding-bottom">
              <el-select
                v-model="filterField.status"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item of statusOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="advanced">
            <el-col :lg="8" :xl="6">
              <el-form-item label="创建时间" class="row-padding-bottom">
                <timeSelection
                  @getStartTimeValue="getStartTimeValue"
                  @getEndTimeValue="getEndTimeValue"
                ></timeSelection>
              </el-form-item>
            </el-col>
          </template>
          <el-col :lg="8" :xl="6">
            <el-form-item label="">
              <a
                @click="toggleAdvanced"
                style="margin-left: 24px; color: #409eff; cursor: pointer"
                class="btnColor"
              >
                {{ advanced ? '收起' : '展开' }}
                <i
                  :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                ></i>
              </a>
              <el-button
                type="primary"
                icon="icon iconfont iconchazhao1"
                @click="searchTable"
                class="searchBtn"
              >
                <span>搜索</span>
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px">
          <el-button
            class="commonBut saveBtn funComBut"
            icon="icon iconfont icontianjia"
            @click="addCommand"
          >
            <span class="opetareText">添加任务</span>
          </el-button>
        </div>
        <!-- 列表 -->
        <el-table
          :data="tableData"
          ref="tableBox1"
          :max-height="tableHeight"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          v-loading="loading"
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column
            align="left"
            prop="typeDesc"
            label="任务类型"
            :formatter="formatTd"
            width="180"
          ></el-table-column>
          <el-table-column
            align="left"
            prop="statusDesc"
            label="任务处理状态"
            :formatter="formatTd"
            width="160"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="startDate"
            label="任务开始时间"
            :formatter="formatTd"
            width="200"
          />
          <el-table-column
            align="center"
            prop="endDate"
            label="任务结束时间"
            :formatter="formatTd"
            width="200"
          />
          <el-table-column label="内容" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.content"
                :columnName="'content'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="method"
            label="请求的方法名"
            :formatter="formatTd"
            width="120"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="createTime"
            label="创建时间"
            :formatter="formatTd"
            width="200"
          />
          <el-table-column align="left" label="操作" width="160" fixed="right">
            <template slot-scope="scope">
              <el-link type="primary" @click="edit(scope.row)">编辑</el-link>
              <el-popover
                placement="top"
                width="200"
                :ref="`popover-${scope.$index}`"
              >
                <p style="line-height: 40px">
                  <i class="el-icon-info" style="color: rgb(255, 153, 0)"></i>
                  您确定删除该内容吗？
                </p>
                <div style="text-align: right; margin: 0">
                  <el-button
                    size="mini"
                    type="text"
                    @click="
                      scope._self.$refs[`popover-${scope.$index}`].doClose()
                    "
                    >取消</el-button
                  >
                  <el-button type="primary" size="mini" @click="del(scope)"
                    >确定</el-button
                  >
                </div>
                <el-link slot="reference" type="primary">删除</el-link>
              </el-popover>
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <!-- filterField为搜索条件 -->
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
          @getpageSize="getpageSize"
          @getpageNo="getpageNo"
        ></Pagination>
      </div>
      <!--添加,修改-->
      <el-dialog
        :title="type === 'add' ? '添加设备命令' : '修改设备命令'"
        :visible.sync="formVisible"
        :close-on-click-modal="false"
        @close="handleCloseForm"
        custom-class="dialog-minwidth"
        :modal-append-to-body="false"
      >
        <el-form
          :model="formData"
          label-width="80px"
          :rules="formRules"
          ref="formData"
          class="form"
        >
          <el-form-item label="任务类型" prop="type" class="row-padding-bottom">
            <el-select
              v-model="formData.type"
              @change="handleChange"
              clearable
              filterable
              placeholder="请选择"
              class="selectWidth"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="formData.type === 'ATTREUP'"
            label="开始时间"
            prop="startDate"
            class="row-padding-bottom"
          >
            <el-date-picker
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              v-model="formData.startDate"
              placeholder="请选择开始时间"
              :append-to-body="false"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            v-if="formData.type === 'ATTREUP'"
            label="结束时间"
            prop="endDate"
            class="row-padding-bottom"
          >
            <el-date-picker
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              v-model="formData.endDate"
              placeholder="请选择结束时间"
              :append-to-body="false"
              align="right"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            v-if="formData.type === 'OTHER'"
            label="方法名称"
            prop="method"
            class="row-padding-bottom"
          >
            <el-input v-model="formData.method" maxlength="30"></el-input>
          </el-form-item>
          <el-form-item
            v-if="formData.type === 'OTHER'"
            label="内容"
            prop="content"
            class="row-padding-bottom"
          >
            <el-input v-model="formData.content" maxlength="30"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="handleCloseForm" class="cancel"
            >取消</el-button
          >
          <el-button
            type="primary"
            @click.native="toSave('formData')"
            class="save"
            v-sdc
            >保存</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import scrollTable from '@/mixin/scrollTable.js'
import common from '@/kits/common'
export default {
  name: 'commandList',
  mixins: [scrollTable],
  data() {
    var checkStartTime = (rule, value, callback) => {
      if (
        this.formData.startDate &&
        this.formData.endDate &&
        this.formData.startDate > this.formData.endDate
      ) {
        callback(new Error('开始时间不能大于结束时间'))
      } else {
        callback()
      }
    }
    var checkEndTime = (rule, value, callback) => {
      if (
        this.formData.startDate &&
        this.formData.endDate &&
        this.formData.startDate > this.formData.endDate
      ) {
        callback(new Error('开始时间不能大于结束时间'))
      } else {
        callback()
      }
    }
    return {
      requestUrl: 'api-att/cs/macMachineTask/expand/list',
      advanced: false,
      loading: false,
      isShow: false,
      typeOptions: [],
      statusOptions: [],
      tableData: [], //表格数据
      filterField: {
        type: '', //任务类型
        machineNo: '', //设备识别号
        status: '', //任务状态
        startDateStr: '', //开始时间
        endDateStr: '', // 结束时间
      },
      pageSize: 20,
      pageNo: 1,
      isShowDetail: '',
      type: 'add',
      id: '',
      formVisible: false,
      commandOptions: [],
      formData: {
        type: '',
        startDate: '',
        endDate: '',
        method: 'none',
        content: 'none',
      },
      formRules: {
        type: [
          { required: true, message: '任务类型不能为空', trigger: 'change' },
        ],
        startDate: [
          { required: true, message: '开始时间不能为空', trigger: 'change' },
          { required: true, validator: checkStartTime, trigger: 'change' },
        ],
        endDate: [
          { required: true, message: '结束时间不能为空', trigger: 'change' },
          { required: true, validator: checkEndTime, trigger: 'change' },
        ],
        method: [
          { required: true, message: '方法名称不能为空', trigger: 'change' },
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: 'change' },
        ],
      },
    }
  },
  created() {
    this.filterField.machineNo = this.$route.query.machineNo
    this.getType()
    this.getStatusOptions()
  },
  mounted() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
  },
  activated() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
    })
  },
  methods: {
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    handleChange(val) {
      this.$refs['formData'].resetFields()
      this.formData = {
        type: val,
        startDate: '',
        endDate: '',
        method: 'none',
        content: 'none',
      }
    },
    // 添加
    addCommand() {
      this.type = 'add'
      this.formVisible = true
    },
    // 修改
    edit(row) {
      this.type = 'edit'
      this.id = row.id
      this.formData = row
      this.formVisible = true
    },
    // 删除
    del(scope) {
      scope._self.$refs[`popover-${scope.$index}`].doClose()
      this.axios({
        method: 'post',
        data: { id: scope.row.id },
        url: 'api-att/cs/macMachineTask/expand/delete',
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.$message({
              message: '删除成功',
              type: 'success',
            })
            this.$refs.pagination.getTableListData()
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {})
    },
    // 关闭弹窗
    handleCloseForm() {
      this.formVisible = false
      this.$refs['formData'].resetFields()
      this.formData = {
        type: '',
        startDate: '',
        endDate: '',
        method: 'none',
        content: 'none',
      }
    },
    // 添加/修改保存
    toSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const { type, startDate, endDate, method, content } = this.formData
          const data = {
            machineNo: this.filterField.machineNo, //设备编号
            type, //任务类型
          }
          switch (type) {
            case 'ATTREUP':
              Object.assign(data, { startDate, endDate })
              break
            case 'OTHER':
              Object.assign(data, { method, content })
              break
            default:
              break
          }
          if (this.type === 'edit') {
            Object.assign(data, { id: this.id })
          }
          const url =
            this.type === 'add'
              ? 'api-att/cs/macMachineTask/expand/add'
              : 'api-att/cs/macMachineTask/expand/update'
          this.axios({
            method: 'post',
            data,
            url,
          })
            .then((response) => {
              if (!response.data.hasError) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                })
                this.handleCloseForm()
                this.$refs.pagination.getTableListData()
              } else {
                this.$message({
                  message: response.data.errorMsg,
                  type: 'error',
                })
              }
            })
            .catch((error) => {})
        } else {
          this.$message({
            message: '请按照规则填写数据',
            type: 'warning',
          })
        }
      })
    },
    goBack() {
      this.$router.push({
        name: 'equipmentMonitor',
        path: '/home/operationManage/equipmentMonitor',
      })
      this.$store.commit('GOBACK_NAME', {
        oldUrl: '/home/operationManage/equipmentMonitor',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    // 列表筛选
    getStartTimeValue(val) {
      if (val) {
        this.filterField.startDateStr = val
      } else {
        this.filterField.startDateStr = ''
      }
    },
    getEndTimeValue(val) {
      if (val) {
        this.filterField.endDateStr = val
      } else {
        this.filterField.endDateStr = ''
      }
    },
    // 任务类型下拉
    getType() {
      this.axios({
        method: 'post',
        url: 'api-att/cs/macMachineTask/expand/getTaskType',
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.typeOptions = response.data.result
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {})
    },
    // 处理状态下拉
    getStatusOptions() {
      this.axios({
        method: 'post',
        url: 'api-att/cs/macMachineTask/expand/getTaskHandleType',
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.statusOptions = response.data.result
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {})
    },
    getTableList(data) {
      this.tableData = data
      this.loading = false
      if (this.tableData.length < 1) {
        this.isShow = true
      }
    },
    //列表查询
    searchTable() {
      this.$refs.pagination.getTableListData()
    },
  },
}
</script>

<style scoped lang="less">
@import '../../../static/css/filterArea.less';
.container {
  .selectWidth {
    width: 100%;
  }
  /deep/ .dialog-minwidth {
    width: 550px;
    .el-date-editor {
      width: 100%;
    }
  }
}
</style>
